package com.yixun.controller;

import com.yixun.entity.YxUser;
import com.yixun.service.UserService;
import com.yixun.util.Const;
import com.yixun.util.LoginValidateImg;
import com.yixun.util.ResponseModel;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController extends BaseController {

    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/")
    public String goLogin(){
       return "login";
    }

    /**
     * 登陆
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(){

      /*  String auth_code = this.getParameterMap().getString("auth_code");*/
    /*    if (!LoginValidateImg.validate(auth_code, this)) {
            return ResponseModel.getModel("验证码错误！","FAIL",null);
        }*/
        return userService.login(this.getParameterMap(), this.getSession(), this.getIpv4());
    }

    /**
     * 跳转主页面
     */
    @RequestMapping(value = "/index")
    public String index(){
        Map<String, Object> session = userService.getUserBySession(this.getSession());
        YxUser sessionUser = (YxUser) session.get("data");
        if (null != sessionUser && !ObjectUtils.isEmpty(sessionUser)) {
            return "index";
        }
        return "redirect:/";
    }

    /**
     * 注销 退出
     */
    @RequestMapping(value = "/logout")
    public String logout(){
        HttpSession session = this.getSession();
        session.removeAttribute(Const.SESSION_ALL_MENU);
        session.removeAttribute(Const.SESSION_USER);
        session.removeAttribute(Const.SESSION_QX);
        return "redirect:/";
    }

    /**
     * 返回Bean对象,用于添加数据时,将空Bean对象原样返回
     */
    @RequestMapping(value = "/copyBeanTJson", method = RequestMethod.POST)
    @ResponseBody
    public Object copyBeanTJson(String bean_name){
        try {
            return Class.forName(bean_name).newInstance();
        } catch (Exception e) {
            return "{}";
        }
    }

    /**
     * 登录验证码
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletResponse response){
        new LoginValidateImg(62, 22, true).getValidateImg(response);
    }

}
